package com.rongmei.jdsync.schedule;

import com.rongmei.jdsync.dto.GoodsDetailInfoResponseDto;
import com.rongmei.jdsync.dto.SkuDataDto;
import com.rongmei.jdsync.entity.Goods;
import com.rongmei.jdsync.service.GoodsService;
import com.rongmei.jdsync.service.JdCategorySyncService;
import com.rongmei.jdsync.service.JdSupplierSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author dongjun
 */
@Component
@Slf4j
public class JdSyncScheduler {

    private static final int PAGE_SIZE = 50;
    private final GoodsService goodsService;
    private final JdCategorySyncService jdCategorySyncService;
    private final JdSupplierSyncService jdSupplierSyncService;

    /**
     * JdSyncScheduler的构造函数。
     *
     * @param goodsService          商品服务接口，用于处理商品相关的业务逻辑。
     * @param jdCategorySyncService 京东商品分类同步服务接口，用于同步京东的商品分类信息。
     * @param jdSupplierSyncService 京东供应商同步服务接口，用于同步京东的供应商信息。
     */
    public JdSyncScheduler(GoodsService goodsService, JdCategorySyncService jdCategorySyncService, JdSupplierSyncService jdSupplierSyncService) {
        this.goodsService = goodsService;
        this.jdCategorySyncService = jdCategorySyncService;
        this.jdSupplierSyncService = jdSupplierSyncService;
    }


    /**
     * 定时任务：同步商品详情
     *
     * &#064;Transactional：声明该方法是一个事务性方法，如果方法执行过程中出现异常，将回滚事务。
     * &#064;Scheduled(cron  = "0 0 1 * * ?")：定时任务的触发表达式，每天凌晨1点执行。
     */
    @Transactional
//    @PostConstruct
    @Scheduled(cron = "0 0 1 * * ?")
    public void syncGoodsDetail() {
        log.info("开始执行定时任务 - 同步商品详情");
        int pageNum = 1;
        boolean hasMorePages = true;

        try {
            while (hasMorePages) {
                List<Goods> goodsList = goodsService.findGoodsByPage(pageNum, PAGE_SIZE);
                hasMorePages = !goodsList.isEmpty();
                for (Goods goods : goodsList) {
                    processGoodsWithRetries(goods);
                }
                pageNum++;
            }

        } catch (Exception e) {
            log.error("定时任务执行失败: {}", e.getMessage(), e);
        }
    }


    /**
     * 商品处理函数
     *
     * @param goods 要处理的商品对象
     * @throws IOException 如果处理过程中发生IO异常，则抛出该异常
     */
    private void processGoodsWithRetries(Goods goods) throws IOException {
        // 获取详情
        GoodsDetailInfoResponseDto dto = jdCategorySyncService.getGoodsDetailInfo(
            String.valueOf(goods.getGoodsId()), "", "");

        // 检查数据
        if (dto.getData() == null) {
            log.warn("数据为空", goods.getGoodsId());
            return;
        }

        // 状态不同
        if (!Objects.equals(goods.getGoodsState(), dto.getData().getGoodsState())) {
            // 获取SKU列表
            List<SkuDataDto> skuData = dto.getData().getSkuData();
            Integer newState = dto.getData().getGoodsState();
            // SKU非空
            if (!skuData.isEmpty()) {
                skuData.forEach(sku -> updateGoodsStateSafely(goods.getGoodsId(), sku.getSkuId(), newState));
            } else {
                // SKU为空
                updateGoodsStateSafely(goods.getGoodsId(), null, newState);
            }
        }
    }


    /**
     * 安全地更新商品状态
     *
     * @param goodsId 商品ID
     * @param skuId SKU ID
     * @param newState 新的商品状态
     */
    private void updateGoodsStateSafely(Long goodsId, Long skuId, Integer newState) {
        try {
            jdSupplierSyncService.updateGoodsState(goodsId, skuId, newState, "auto");
        } catch (Exception e) {
            log.error("更新商品状态失败，商品ID: {}, SKU ID: {}, 新状态: {}, 异常: {}",
                    goodsId, skuId, newState, e.getMessage(), e);
        }
    }


}
